import BaseButton from '@/components/base/BaseButton';
import BaseForm, {
  BaseFormDight,
  BaseFormSelect,
  BaseFormText,
  BaseFormUpload,
  BaseModalForm,
  ProFormDependency,
  ProFormRadio
} from '@/components/base/BaseForm';
import { ModalFC } from '@/components/base/BaseModal';
import BaseTree from '@/components/base/BaseTree';
import { getRealFileUrl } from '@/config/config';
import { TrueFalseEnum } from '@/models';
import { getRadarTreeNoDoList } from '@/pages/radar/RadarInfo/api';
import { isEmpty } from '@/utils/is';
import { useRequest } from '@/utils/request';
import { Alert, Col, FormInstance, Image, Row, Spin } from 'antd';
import { useRef, useState } from 'react';
import { RealFileStrutureModel } from '../../data';
import { getList as getDataTypeList } from '../../DataTypeInfo/api';
import {
  getChildList as getDisplayLocationChildList,
  getList as getDisplayLocationList
} from '../../DisplayLocation/api';
import { getList as getFileTypeList } from '../../FileTypeInfo/api';
import { addInfo, editInfo } from '../api';
import StatuList from './SubSystemStatusListModal/List';

const flatten = (list: Record<string, any>[] = [], parentIds: string[]) => {
  list.forEach((item: any) => {
    item.allId = parentIds.length > 0 ? `${parentIds.join('-')}-${item.id}` : item.id;
    if (item.children) {
      flatten(item.children, [...parentIds, item.id]);
    }
  });
  return list;
};
const InfoModal: ModalFC<{ data?: RealFileStrutureModel; readonly?: boolean }> = (props) => {
  const { data = {} as RealFileStrutureModel, readonly = false, onSuccess, ...anyProps } = props;
  const { id, systemId, extensionId, keyPartsModelId } = data;
  const isadd = isEmpty(id);
  const [realReadOnly, setRealReadOnly] = useState(() => readonly);
  const [key, setKey] = useState(() =>
    [systemId, extensionId, keyPartsModelId].filter((i) => i).join('-')
  );
  const tree = useRequest(getRadarTreeNoDoList);
  const formRef = useRef<FormInstance>();
  return (
    <BaseModalForm<RealFileStrutureModel>
      title='实时文件结构信息'
      labelCol={{ style: { width: 100 } }}
      width={1200}
      formRef={formRef}
      initialValues={{
        ...{ importantPara: TrueFalseEnum.enum.false, isStatus: TrueFalseEnum.enum.false },
        ...data,
        allId: key
      }}
      {...anyProps}
      submitter={realReadOnly ? false : {}}
      onFinish={async (values) => {
        values.id = id;
        const [systemId, extensionId = '', keyPartsModelId = ''] = key.split('-');
        values.systemId = systemId === '' ? undefined : systemId;
        values.extensionId = extensionId;
        values.keyPartsModelId = keyPartsModelId;
        if (!values.displayLocationPId) {
          values.displayLocationId = '';
        }
        const { ok } = await (isadd ? addInfo : editInfo)(values);
        ok && onSuccess && onSuccess();
        return ok;
      }}
    >
      {!isadd && (
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
          <div style={{ fontSize: 16 }}>实时文件结构基础信息</div>
          <BaseButton
            type='primary'
            code='edit'
            onClick={() => {
              setRealReadOnly(!realReadOnly);
              formRef.current?.resetFields();
            }}
          >
            {realReadOnly ? '编辑' : '详情查看'}
          </BaseButton>
        </div>
      )}
      <Row>
        <Col span={8}>
          <ProFormRadio.Group
            label='大屏展示'
            name='isLargeScreen'
            radioType='button'
            readonly={realReadOnly}
            options={TrueFalseEnum.list}
            placeholder='请选择数据是否在大屏显示'
            rules={[{ required: true, message: '请选择数据是否在大屏显示' }]}
          />
          <ProFormRadio.Group
            label='是否整机'
            name='isComplete'
            readonly={realReadOnly}
            radioType='button'
            options={TrueFalseEnum.list}
            placeholder='请选择数据是否为整机数据'
            rules={[{ required: true, message: '请选择数据是否为整机数据' }]}
          />
          <ProFormDependency name={['isComplete']}>
            {({ isComplete }) => {
              return isComplete === TrueFalseEnum.enum.false ? (
                <BaseForm.Item
                  name='allId'
                  label='雷达结构'
                  rules={[{ required: true, message: '请选择雷达结构' }]}
                >
                  <Spin spinning={tree.loading}>
                    <BaseTree
                      blockNode
                      defaultExpandAll
                      height={400}
                      bindProps={{ key: 'allId', value: 'allId', title: 'name' }}
                      treeData={flatten(tree.data, [])}
                      onSelect={(keys, { node }) => {
                        if (!realReadOnly) {
                          const { allId } = node as unknown as Record<string, string>;
                          setKey(allId);
                          const value = formRef.current?.getFieldsValue(true);
                          formRef.current?.setFieldsValue({ ...value, allId });
                        }
                      }}
                    />
                  </Spin>
                </BaseForm.Item>
              ) : (
                <Alert type='info' message='数据已为整机数据，无需选择雷达结构' />
              );
            }}
          </ProFormDependency>
        </Col>
        <Col span={16}>
          <Row>
            <Col span={8}>
              <BaseFormText
                label='中文名称'
                readonly={realReadOnly}
                name='cname'
                placeholder='请输入中文名称'
                fieldProps={{ maxLength: 20, showCount: true }}
                rules={[
                  { required: true, message: '请输入中文名称' },
                  { type: 'string', max: 20, message: '长度不可超过20位' }
                ]}
              />
            </Col>
            <Col span={8}>
              <BaseFormText
                label='英文名称'
                readonly={realReadOnly}
                name='ename'
                placeholder='请输入英文名称'
                fieldProps={{ maxLength: 50, showCount: true }}
                rules={[
                  { required: true, message: '请输入英文名称' },
                  { type: 'string', max: 50, message: '长度不可超过50位' },
                  {
                    pattern: /^[a-zA-Z][0-9a-zA-Z_-]*$/g,
                    message: '英文名称只能包括大小写字母、数字、下划线、短横线,只能以字母作为开头'
                  }
                ]}
              />
            </Col>
            <Col span={8}>
              <BaseFormDight
                label='数据序号'
                readonly={realReadOnly || !isadd}
                name='dataSerial'
                fieldProps={{ step: 1, min: 1 }}
                rules={[{ required: true, message: '请输入数据序号' }]}
              />
            </Col>
            <Col span={8}>
              <BaseFormSelect
                label='数据类型'
                readonly={realReadOnly}
                name='dataTypeId'
                request={getDataTypeList}
                placeholder='请选择数据类型'
                fieldProps={{
                  defaultSelectedOptions: [{ name: data.dataTypeName, id: data.dataTypeId }],
                  fieldNames: { label: 'name', value: 'id' }
                }}
                rules={[{ required: true, message: '请选择数据类型' }]}
              />
            </Col>
            <Col span={8}>
              <BaseFormSelect
                label='文件类型'
                readonly={realReadOnly}
                name='fileTypeId'
                request={getFileTypeList}
                placeholder='请选择文件类型'
                fieldProps={{
                  defaultSelectedOptions: [{ name: data.fileTypeName, id: data.fileTypeId }],
                  fieldNames: { label: 'name', value: 'id' }
                }}
                rules={[{ required: true, message: '请选择文件类型' }]}
              />
            </Col>
            <Col span={8}>
              <BaseFormDight
                readonly={realReadOnly}
                label='数据长度'
                name='length'
                fieldProps={{ step: 1, min: 1 }}
                rules={[{ required: true, message: '请输入数据长度' }]}
              />
            </Col>
            <Col span={8}>
              <ProFormDependency name={['isLargeScreen', 'fileTypeId']}>
                {({ fileTypeId }) => (
                  <BaseFormSelect
                    label='显示位置'
                    readonly={realReadOnly}
                    name='displayLocationPId'
                    request={getDisplayLocationList}
                    placeholder='请选择显示位置'
                    fieldProps={{
                      params: { radarFileType: fileTypeId },
                      defaultSelectedOptions: [
                        { name: data.displayLocationPName, id: data.displayLocationPId }
                      ],
                      fieldNames: { label: 'name', value: 'id' }
                    }}
                    // rules={[{ required: isLargeScreen, message: '请选择显示位置' }]}
                  />
                )}
              </ProFormDependency>
            </Col>
            <Col span={8}>
              <ProFormDependency name={['displayLocationPId']}>
                {({ displayLocationPId }) => {
                  return (
                    <BaseFormSelect
                      label='排序位置'
                      readonly={realReadOnly}
                      name='displayLocationId'
                      hiddenItem={!displayLocationPId}
                      hiddenRender={() => <Alert message='请先选择显示位置' type='warning' />}
                      request={getDisplayLocationChildList}
                      placeholder='请选择排序位置'
                      fieldProps={{
                        params: { pid: displayLocationPId },
                        defaultSelectedOptions: [
                          { name: data.displayLocationName, id: data.displayLocationId }
                        ],
                        fieldNames: { label: 'name', value: 'id' }
                      }}
                      // rules={[{ required: isLargeScreen, message: '请选择排序位置' }]}
                    />
                  );
                }}
              </ProFormDependency>
            </Col>
            <Col span={8}>
              <ProFormRadio.Group
                label='状态字段'
                readonly={realReadOnly}
                name='isStatus'
                radioType='button'
                options={TrueFalseEnum.list}
              />
            </Col>
            <Col span={8}>
              <ProFormRadio.Group
                label='重要参数'
                readonly={realReadOnly}
                name='importantPara'
                radioType='button'
                options={TrueFalseEnum.list}
              />
            </Col>

            <Col span={8}>
              <BaseFormDight
                readonly={realReadOnly}
                label='倍数'
                name='scale'
                fieldProps={{ step: 1, min: 0 }}
                rules={[{ required: true, message: '请输入数据倍数' }]}
              />
            </Col>
            <Col span={8}>
              <BaseFormDight
                readonly={realReadOnly}
                label='最小值'
                name='min'
                placeholder='请输入数据最小值'
                fieldProps={{ step: 1 }}
                rules={[
                  // { required: true, message: '请输入数据最小值' },
                  (form) => ({
                    validator: (rule, value, callback) => {
                      const max = form.getFieldValue('max');
                      if (isEmpty(max) || max >= value) {
                        callback();
                        return;
                      }
                      callback('最小值应小于最大值');
                    }
                  })
                ]}
              />
            </Col>
            <Col span={8}>
              <BaseFormDight
                label='最大值'
                readonly={realReadOnly}
                name='max'
                placeholder='请输入数据最大值'
                fieldProps={{ step: 1 }}
                rules={[
                  // { required: true, message: '请输入数据最大值' },
                  (form) => ({
                    validator: (rule, value, callback) => {
                      const min = form.getFieldValue('min');
                      if (isEmpty(min) || min <= value) {
                        callback();
                        return;
                      }
                      callback('最大值应大于最小值');
                    }
                  })
                ]}
              />
            </Col>
            <Col span={8}>
              <BaseFormText
                label='单位'
                readonly={realReadOnly}
                name='unit'
                placeholder='请输入数据单位'
                fieldProps={{ maxLength: 10, showCount: true }}
                rules={[
                  // { required: true, message: '请输入数据单位' },
                  { type: 'string', max: 10, message: '长度不可超过10位' }
                ]}
              />
            </Col>
            <Col span={12}>
              {realReadOnly ? (
                <BaseForm.Item label='参数图片' name='icon'>
                  {data.icon ? (
                    <Image src={getRealFileUrl(data.icon)} width={50} height={50} />
                  ) : (
                    '暂无图片'
                  )}
                </BaseForm.Item>
              ) : (
                <BaseFormUpload
                  label='参数图片'
                  name='icon'
                  accept='.jpg,.png,.gif'
                  extra='只能上传jpg、png、gif，且不可超过100M'
                  fieldProps={{
                    showUrl: false,
                    preview: (url) => (
                      <div style={{ marginTop: 10 }}>
                        {url && <Image src={url} width={50} height={50} />}
                      </div>
                    )
                  }}
                />
              )}
            </Col>
          </Row>
        </Col>
      </Row>
      {id && realReadOnly && data.isStatus === TrueFalseEnum.enum.true && (
        <StatuList systemId={data.systemId} id={`${data.dataSerial}`} height={200} />
      )}
    </BaseModalForm>
  );
};

export default InfoModal;
